package com.example.myblog.service.impl;

import com.example.myblog.dao.UserDao;
import com.example.myblog.pojo.User;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.service.impl
 * @ClassName UserServiceImpl
 * @CreateTime: 2025-05-28  22:59
 * @Author: TangLiFei
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    // 关联查询用户及权限
    @Override
    public User findUserWithAuthorities(User user) {
        System.out.println("传入的账号: " + user.getAccount());
        System.out.println("传入的密码: " + user.getPwd());
        List<User> userList=userDao.findUserWithAuthorities(user.getAccount(), user.getPwd());
        System.out.println("查询到的用户列表：" + userList);
        // 将查询结果合并为一个包含所有权限的用户对象
        return userList.isEmpty() ? null : mergeUserAuthorities(userList);
    }

    // 辅助方法：合并同一用户的多个权限记录
    private User mergeUserAuthorities(List<User> userList) {
        if (userList.isEmpty()) return null;

        User mergedUser=new User();
        mergedUser.setId(userList.get(0).getId());
        mergedUser.setAccount(userList.get(0).getAccount());
        mergedUser.setPwd(userList.get(0).getPwd());

        List<String> authorities=new ArrayList<>();
        for (User user : userList) {
            if (user.getAuthorities() != null) {
                authorities.addAll(user.getAuthorities());
            }
        }
        mergedUser.setAuthorities(authorities);
        return mergedUser;
    }

    @Override
    public User findUserByAccountAndPwd(User user) {
        User user1=userDao.findUserByAccountAndPwd(user);
        return user1;
    }

    @Override
    public List<User> findAllUsers() {
        return userDao.findAllUsers();
    }

    @Override
    public void deleteUserById(int id) {
        userDao.deleteUserById(id);
    }

    @Override
    public void register(User user) {
        User existingUser = userDao.findByAccount(user.getAccount());
        if (existingUser != null) {
            // 若存在，抛出异常，让 Controller 捕获处理
            throw new RuntimeException("该账号已存在，请更换账号注册");
        }
        try {
            userDao.insertUser(user);
            // 插入关联数据，这里假设默认权限 ID 为 2
            int authorityId = 2;
            int accountId = user.getId(); // 需要在插入用户后获取用户 ID
            userDao.insertAccountAuthority(accountId, authorityId);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("注册失败，插入关联数据时出现异常", e);
        }
    }
}
